//
//  YZPigSearchResultController.m
//  VET
//
//  Created by 刘文靖 on 2018/7/30.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZPigSearchResultController.h"
#import "YZSwineArchieveCell.h"
#import "YZActionSheet.h"
#import "YZPigModel.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "YZPigDocVC.h"
#import "YZRouter+AutoVC.h"
#import "YZCreateNoteVC.h"
#import "YZAutoFormHeader.h"
#import "YZWorkNoteModel.h"
#import "YZPopupController.h"
#import "YZPopupCustomView.h"
#import "YZWorkbenchAPI.h"
#import "YZSearchBar.h"
@interface YZPigSearchResultController ()<UITableViewDelegate,UITableViewDataSource,YZSwineArchieveCellDelegate,YZActionSheetDelegate,UISearchBarDelegate>
@property (strong, nonatomic) NSMutableArray<YZPigModel *> *dataSource;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) YZPigModel *selectedModel;
@property (strong, nonatomic) NSString *earMark;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) YZSearchBar *searchBar;
@end

@implementation YZPigSearchResultController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColorWithHex(0xffffff);
    [self setupMainView];
    [self setupRefresh];
}


- (void)setupMainView{
   self.cancelBtn = [[UIButton alloc] init];
    [self.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelBtn setTitleColor:kColorWithHex(0x434343) forState:UIControlStateNormal];
    self.cancelBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18];
    [self.view addSubview:self.cancelBtn];
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(36, 18));
        make.left.offset(18);
        make.top.offset(11 + kStatusBarHeight);
    }];
    [self.view addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(kScreenWidth - 80, 36));
        make.left.mas_equalTo(self.cancelBtn.mas_right).offset(0);
        make.top.offset(kStatusBarHeight);
    }];

    @weakify(self)
    [[self.cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (void)setupRefresh {
    
    // 设置刷新控件
    @weakify(self)
    
    // header
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self loadNewData];
    }];
    self.tableView.mj_header = header;
    
    // footer
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        [self loadMoreData];
    }];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}


- (void)loadNewData{
    if (self.earMark.length == 0){
        [self.tableView.mj_header endRefreshing];
        return;
    }
    @weakify(self)
    [[YZPigModelAPI requestSwineList:0 earMark:self.earMark type:nil] subscribeNext:^(NSDictionary *dict) {
        @strongify(self)
        self.dataSource = [YZPigModel mj_objectArrayWithKeyValuesArray:dict[@"list"]];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self)
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData{
    //[self.tableView.mj_footer endRefreshing];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = kColorWithHex(0xE9EAEB);
        _tableView.rowHeight = 192;
        [_tableView registerClass:[YZSwineArchieveCell class] forCellReuseIdentifier:@"YZSwineArchieveCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.offset(0);
            make.top.offset(44 + kStatusBarHeight);
        }];
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    return _tableView;
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZSwineArchieveCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YZSwineArchieveCell"];
    cell.model = self.dataSource[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YZPigDocVC *pigDocVC = [YZPigDocVC new];
    pigDocVC.model = self.dataSource[indexPath.row];

    [[YZRouter sharedInstance] pushVC:pigDocVC];
}

#pragma mark - YZSwineArchieveCellDelegate
- (void)cellDidClickManage:(YZSwineArchieveCell *)cell{
    YZActionSheet *sheet = [[YZActionSheet alloc] initWithTitle:nil sheetTitles:@[@"编辑修改",@"死淘登记",@"添加笔记",@"删除"] cancleBtnTitle:@"取消" sheetStyle:YZActionSheetDefault delegate:self];
    sheet.sheetHeight = 54;
    self.selectedModel = cell.model;
    [sheet show];
}

#pragma mark - YZActionSheetDelegate
/**
 点击actionSheet代理方法
 
 @param actionSheet actionSheet
 @param buttonIndex index
 */
- (void)actionSheet:(YZActionSheet *)actionSheet clickButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0://编辑修改
        {
            NSString *swineryId = [@(self.selectedModel.pigId) stringValue];
            [[YZRouter sharedInstance] yz_atuoPush:@"cardNewSwine" params:@{@"params" : @{kURI : kURI, @"id" : swineryId}} itemClick:nil];
        }
            break;
            
        case 1://死亡登记
        {
            // 死淘登记
            NSString *swineryId = [@(self.selectedModel.pigId) stringValue];
            [[YZRouter sharedInstance] yz_atuoPush:@"cardDeadSignSwine" params:@{@"params" : @{@"id" : swineryId, @"earMark" : self.selectedModel.earMark}} itemClick:nil ];
        }
            break;
            
        case 2://添加笔记
        {
            YZCreateNoteVC *noteVC = [[YZCreateNoteVC alloc] init];
            NSMutableArray *archiveList = [NSMutableArray array];
            [archiveList addObject:[YZArchiveModel convertWithPig:self.selectedModel]];
            noteVC.archiveList = archiveList;
            
            [[YZRouter sharedInstance] pushVC:noteVC];
        }
            break;
            
        case 3://删除
        {
            YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
            @weakify(self)
            [customView setupUIWithTitle:nil message:[NSString stringWithFormat:@"确定要删除%@猪只？删除后不可恢复当前猪只已记录信息。",self.selectedModel.earMark] confirmTitle:@"删除" cancelTitle:@"取消" confirmHandler:^{
                
                @strongify(self)
                // 删除猪只
                NSString *swineryId = [@(self.selectedModel.pigId) stringValue];
                [[YZWorkbenchAPI deleteSwineAPI:swineryId] subscribeNext:^(id  _Nullable x) {
                    
                    [self.dataSource removeObject:self.selectedModel];
                    [self.tableView reloadData];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kSwineRefreshNotification object:nil];
                    [self.YZ_popupController dismiss];
                    
                } error:^(NSError * _Nullable error) {
                    
                    [self.YZ_popupController dismiss];
                }];
                
            } cancelHandler:^{
                [self.YZ_popupController dismiss];
            }];
            [self.YZ_popupController presentContentView:customView];
        }
            break;
            
        default:
            break;
    }
}
- (void)actionSheetCancle:(YZActionSheet *)actionSheet{
    
}

#pragma mark - getter && setter
-(YZSearchBar *)searchBar{
    if (!_searchBar){
        _searchBar = [[YZSearchBar alloc] init];
        _searchBar.backgroundColor = [UIColor clearColor];
        _searchBar.delegate = self;
        //光标颜色
        _searchBar.cursorColor = kColorWithHex(0x32BE60);
        //TextField
        _searchBar.searchBarTextField.backgroundColor = kColorWithHex(0xFAFAFA);
        _searchBar.searchBarTextField.layer.cornerRadius = 10;
        _searchBar.searchBarTextField.layer.masksToBounds = YES;
        _searchBar.searchBarTextField.layer.borderColor = kColorWithHex(0xFAFAFA).CGColor;
        _searchBar.searchBarTextField.layer.borderWidth = 1.0;
        _searchBar.searchBarTextField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        _searchBar.searchBarTextField.placeholder = @"搜索";
        _searchBar.delegate = self;
        //去掉取消按钮灰色背景
        _searchBar.hideSearchBarBackgroundImage = YES;
        [_searchBar.searchBarTextField becomeFirstResponder];
    }
    return _searchBar;
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.view endEditing:YES];
    self.earMark = searchBar.text;
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
}


@end
